import { useParams, history } from '@umijs/max';
import styles from './index.less';
import { DownOutlined, MinusOutlined, PlusOutlined, UpOutlined } from '@ant-design/icons';
import { Image, Input, InputNumber, message, Space } from 'antd';
import classnames from 'classnames';
import { useRef, useState } from 'react';
import CollectIcon from '../components/icons/Collect';
import { useRequest } from 'ahooks';
import { favoriteGoods, getGoodsDetails, removeFavorite } from '@/services/details';
import { money } from '@/utils/money';
import { actionList } from './const';
import CollectOkIcon from '../components/icons/CollectOk';
import { isLoginStatus } from '@/utils/isLoginStatus';
import { cartAdd } from '@/services/shoppingCar';

const guigeCard = (item, activeGuige, setActiveGuige) => {
    return (
        <div className={classnames(styles.guigeCard, activeGuige.id === item.id ? styles.activeGuige : '')} onClick={() => setActiveGuige(item)}>
            <Image width={36} height={36} preview={false} src={item?.picture} />
            <div style={{ marginLeft: 10 }}>{item?.name}</div>
        </div>
    )
}

const Details = () => {
    const id = useParams().id;
    const contentRed = useRef<HTMLDivElement>(null);
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))

    const [isCollect, setIsCollect] = useState(false);
    const [activePicture, setActivePicture] = useState(null);
    const [activeGuige, setActiveGuige] = useState<any>(null);
    const [quantity, setQuantity] = useState(1);
    const pictureListRef = useRef<HTMLDivElement>(null);

    const {data: goodsDetails} = useRequest(() => {
        return getGoodsDetails({id}).then(res => {
            if (res.code === 200) {
                setActiveGuige(res.data?.skuList?.[0])
            }
            return res.data;
        })
    },{
        refreshDeps: [id]
    })
    
    const scrollTopNum = () => {
        if (pictureListRef.current) {
            const scrollTop = pictureListRef.current.scrollTop;
            pictureListRef.current?.scrollTo({
                top: scrollTop - 400,
                behavior: 'smooth'
            });
        }
    }
    const scrollBottomNum = () => {
        if (pictureListRef.current) {
            const scrollBottom = pictureListRef.current.scrollTop;
            pictureListRef.current?.scrollTo({
                top: scrollBottom + 400,
                behavior: 'smooth'
            });
        }
    }

    // 收藏商品
    const favoriteHandle = () => {
        const isLogin = isLoginStatus()
        if (!isLogin) return
        if (!goodsDetails?.id || !activeGuige?.id) {
            return
        }
        const data = {
            goodsId: goodsDetails?.id,
            userId: userInfo?.id,
            skuId: activeGuige?.id,
        }
        
        favoriteGoods(data).then((res) => {
            if (res.code === 200) {
                message.success('收藏成功')
                setIsCollect(true)
            } else {
                message.warning(res.message)
            }
        })
    }
    // 删除收藏
    const removeFavoriteHandle = () => {
        if (!goodsDetails?.id || !activeGuige?.id) {
            return
        }
        const data = {
            goodsId: goodsDetails?.id,
            userId: userInfo?.id,
            skuId: activeGuige?.id,
        }
        removeFavorite(data).then((res) => {
            if (res.code === 200) {
                message.success('删除成功')
                setIsCollect(false)
            } else {
                message.warning(res.message)
            }
        })
    }

    const createOrder = () => {
        if (!isLoginStatus()) return
        history.push('/createOrder', {
            skuList: [{
                ...activeGuige,
                quantity,
                skuId: activeGuige.id,
                goodsName: goodsDetails?.name,
            }]
        })
    }

    const addShoppingCar = () => {
        if (!isLoginStatus()) return
        cartAdd({
            goodsId: goodsDetails?.id,
            skuId: activeGuige?.id,
            quantity: quantity,
        }).then((res) => {
            if (res.code === 200) {
                message.success('加入购物车成功')
            } else {
                message.warning(res.message)
            }
        })
    }
    return (
        <div className={styles.page} ref={contentRed}>
            <div className={styles.topName}>
                谷雨包材
            </div>
            <div style={{ display: 'flex' }}>
                <div className={styles.pictureContent}>
                    <div className={styles.verticalPic}>
                        <div onClick={scrollTopNum} className={styles.scorllTop}>
                            <UpOutlined />
                        </div>
                        <div onClick={scrollBottomNum} className={styles.scorllBottom}>
                            <DownOutlined />
                        </div>
                        <div className={styles.pictureList} ref={pictureListRef}>
                            {
                                goodsDetails?.goodsImageBanners?.map((item, index) => {
                                    return (
                                        <div 
                                            key={index} 
                                            className={classnames(styles.picture, activePicture === item ? styles.activePic : '')}
                                            onClick={() => setActivePicture(item)}
                                        >
                                            <Image width={100} height={100} preview={false} src={item} />
                                        </div>
                                    )
                                })
                            }
                        </div>
                    </div>
                    <div className={styles.zhuPic}>
                        <Image width={"100%"} height={"100%"} preview={false} src={activePicture ? activePicture : goodsDetails?.picture} />
                    </div>
                </div>
                <div className={styles.info}>
                    <div className={styles.infoTop}>
                        <div className={styles.goodsName}>{goodsDetails?.name}</div>
                        <div className={styles.collect}>
                            {
                                isCollect ? 
                                <div onClick={removeFavoriteHandle}>
                                    <CollectOkIcon style={{fontSize: 14, marginRight: 10}} />
                                </div>
                                : <div onClick={favoriteHandle}>
                                    <CollectIcon style={{fontSize: 16, marginRight: 10}} />
                                  </div> 
                            }
                            <div>
                                收藏
                            </div>
                        </div>
                    </div>
                    <div className={styles.des}>
                        免费送样 · 定金发货 · 可开发票
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div style={{ color: 'red', fontSize: '18px', display: 'flex', alignItems: 'center' }}>
                            ¥ &nbsp; <div style={{ fontSize: '28px', fontWeight: 600 }}>{money(activeGuige?.price)}</div>
                        </div>
                        <div style={{ display: 'flex', fontWeight: 300 }}>
                            累计销量 &nbsp;
                            <div style={{ fontWeight: 500 }}>{goodsDetails?.salesNum || 0}</div>
                        </div>
                    </div>
                    <div style={{ display: 'flex', marginTop: 20, fontWeight: 300 }}>
                        <div style={{ marginRight: 30 }}>规格</div>
                        <div className={styles.guigeList}>
                            {
                                goodsDetails?.skuList?.map((item, index) => {
                                    return guigeCard(item, activeGuige, setActiveGuige);
                                })
                            }
                        </div>
                    </div>
                    <div style={{ display: 'flex', marginTop: 20, fontWeight: 300, alignItems: 'center' }}>
                        <div style={{ marginRight: 30 }}>数量</div>
                        <div className={styles.quantity}>
                            <InputNumber controls={false} value={quantity} addonBefore={<PlusOutlined onClick={() => {
                                setQuantity(quantity + 1)
                            }} />} addonAfter={<MinusOutlined onClick={() => {
                                if (quantity > 1) {
                                    setQuantity(quantity - 1)
                                }
                            }} />} />
                        </div>
                    </div>
                    <div className={styles.btn}>
                        <div onClick={addShoppingCar} style={{ background: 'rgb(243,207,153)', width: '40%' }}>加入购物车</div>
                        <div onClick={createOrder} style={{ background: 'rgb(238,128,55)', width: '60%' }}>立即购买</div>
                    </div>
                </div>
            </div>
            <div style={{ fontSize: '30px', fontWeight: 600, marginTop: 30, marginBottom: 30, width: '1430px' }}>产品详情</div>
            <div className={styles.goodsDetails}>
                <div dangerouslySetInnerHTML={{__html: goodsDetails?.detailsDescribe ? JSON.parse(goodsDetails?.detailsDescribe) : ''}}></div>
            </div>
            <div className={styles.floatBtn}>
                <Space size={20} direction="vertical">
                    {
                        actionList.map((item) => {
                            return (
                                <div key={item.name} className={styles.floatBtnItem} onClick={() => {
                                    if (item.url === 'top') {
                                        contentRed?.current?.scrollTo({
                                            top: 0,
                                            behavior: 'smooth'
                                        })
                                    } else {
                                        history.push(item.url)
                                    }
                                }}>
                                    {item.icon}
                                    <span style={{ marginTop: 10 }}>{item.name}</span>
                                </div>
                            )
                        })
                    }
                </Space>
            </div>
        </div>
    )
}

export default Details;